package org.example;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

public class PushInformHttpServer {
    private String bindAddress;
    private int port;
    private ServerSocket serverSocket;
    private boolean isRunning;

    public PushInformHttpServer(String ipAddress, int port) {
        this.bindAddress = ipAddress;
        this.port = port;
    }

    public void start() throws IOException {
        isRunning = true;
        InetAddress inetAddress = InetAddress.getByName(bindAddress);
        serverSocket = new ServerSocket(port, 50, inetAddress);

        System.out.println("Server started on " + bindAddress + ":" + port);
        System.out.println("Available on:");
        System.out.println("http://" + bindAddress + ":" + port);
        if (bindAddress.equals("0.0.0.0")) {
            System.out.println("And all other available interfaces");
        }

        java.util.concurrent.ExecutorService executor = Executors.newFixedThreadPool(10);

        while (isRunning) {
            try {
                Socket clientSocket = serverSocket.accept();
                executor.execute(() -> handleRequest(clientSocket));
            } catch (IOException e) {
                if (isRunning) {
                    System.err.println("Error accepting connection: " + e.getMessage());
                }
            }
        }
    }

    private void handleRequest(Socket clientSocket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             OutputStream out = clientSocket.getOutputStream()) {

            // 读取请求头
            StringBuilder requestHeaders = new StringBuilder();
            String line;
            int contentLength = 0;
            while ((line = in.readLine()) != null && !line.isEmpty()) {
                requestHeaders.append(line).append("\n");
                if (line.startsWith("Content-Length:")) {
                    contentLength = Integer.parseInt(line.substring("Content-Length:".length()).trim());
                }
            }

            // 读取请求体
            StringBuilder requestBody = new StringBuilder();
            if (contentLength > 0) {
                char[] buffer = new char[contentLength];
                int bytesRead = in.read(buffer, 0, contentLength);
                requestBody.append(buffer, 0, bytesRead);
            }

            // 打印接收到的完整请求
            System.out.println("=== 接收到的请求 ===");
            System.out.println(requestHeaders);
            System.out.println("\n请求体内容:");
            System.out.println(requestBody);
            System.out.println("=================");

            // 发送响应
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type: text/plain\r\n" +
                    "\r\n" +
                    "{\"errcode\":\"0\",\"msg\":\"ok\"}";
//                    "已收到您的POST请求，内容长度为: " + contentLength + " 字节";
            out.write(response.getBytes(StandardCharsets.UTF_8));

        } catch (Exception e) {
            System.err.println("Error handling request: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("Error closing client socket: " + e.getMessage());
            }
        }
    }

    public void stop() {
        isRunning = false;
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            System.err.println("Error closing server: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 默认绑定所有可用IP
        String ipAddress = "192.168.23.207";
        int port = 9096;

        // 从命令行参数读取IP和端口
        if (args.length > 0) {
            ipAddress = args[0];
            if (args.length > 1) {
                port = Integer.parseInt(args[1]);
            }
        }

        PushInformHttpServer server = new PushInformHttpServer(ipAddress, port);
        try {
            server.start();
        } catch (IOException e) {
            System.err.println("Failed to start server: " + e.getMessage());
        }
    }
}